package com.weiya.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * <p class="detail">
 * 功能:读取properties文件值
 * </p>
 *
 * @author BaoWeiwei
 * @ClassName Properties util.
 * @Version V1.0.
 * @date 2018.07.13 10:22:21
 */
public class PropertiesUtil extends PropertyPlaceholderConfigurer {

    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static Map<String, String> propMap;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
            throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        propMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            props.put(keyStr, value);
        }
    }

    /**
     * Gets property.
     * static method for accessing context properties
     *
     * @param name the name
     * @return the property
     */
    public static String getProperty(String name) {
        return propMap.get(name);
    }



    public Map<String, String> getProperties(Map<String, String> map,String fileName){
        Properties props = new Properties();
        try {
            InputStream in = getClass().getResourceAsStream(fileName);
            props.load(in);
            Enumeration en = props.propertyNames();
            while (en.hasMoreElements()) {
                String key=(String) en.nextElement();
                String property=props.getProperty(key);
                map.put(key, property);
            }
        } catch (Exception e) {
            logger.error("read file to map failed");
        }
        return map;
    }
}
